package com.tedu.day9.lambda;

import java.util.Arrays;
import java.util.Comparator;

public class TestLambda {
    public static void main(String[] args) {
        Person[] person = {
                new Person("cao",18),
                new Person("chao",38),
                new Person("chen",28),
                new Person("ren",8)
        };
        Arrays.sort(person, (p1,p2)->{
            return p1.getAge() - p2.getAge();
        });

        for (int i = 0; i < person.length; i++) {
            System.out.println(person[i]);
        }
        System.out.println("===========");
        Arrays.sort(person, (p1,p2)-> {
            return (int)p1.getName().charAt(0) - (int)p2.getName().charAt(0);
        } );
        for (int i = 0; i < person.length; i++) {
            System.out.println(person[i]);
        }
        System.out.println("=================");

        Arrays.sort(person, get());
        for (int i = 0; i < person.length; i++) {
            System.out.println(person[i]);
        }

        System.out.println("===================");
        Arrays.sort(person, (p1,p2)-> {
            for (int i = 0; i < p2.getName().length(); i++) {
                if(p2.getName().charAt(i) > p1.getName().charAt(i)){
                    return 1;
                }
                if(p2.getName().charAt(i) < p1.getName().charAt(i)){
                    return -1;
                }
            }
            return 0;
        } );
        for (int i = 0; i < person.length; i++) {
            System.out.println(person[i]);
        }
    }

    public static Comparator<Person> get(){
       Comparator<Person> com = new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                for (int i = 0; i < o1.getName().length(); i++) {
                    if(o1.getName().charAt(i) > o2.getName().charAt(i)){
                        return 1;
                    }
                    if(o1.getName().charAt(i) < o2.getName().charAt(i)){
                        return -1;
                    }
                }
                return 0;
            }
        };
       return com;
    }

}
